package com.itjcloud.iot.gateway.service.impl;

import com.itjcloud.iot.gateway.model.CommonTokenInfo;
import com.itjcloud.iot.gateway.service.ItjJwtDecoderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;


@Service
@Slf4j
@RequiredArgsConstructor
public class ItjJwtDecoderServiceImpl implements ItjJwtDecoderService {

    private final ReactiveRedisTemplate<String, CommonTokenInfo> loginInfoReactiveRedisTemplate;
    String LOGIN_KEY = "itj:auth:";
    private final JwtDecoder jwtDecoder;

    @Override
    public Mono<CommonTokenInfo> getPayloadToUserInfo(String token) {
        return Mono.just(token)
                .map(jwtDecoder::decode) // 解码JWT
                .map(CommonTokenInfo::new) // 获取声明
                //TODO: 抛出异常.统一处理
                .onErrorMap(e -> new JwtException("jwt解密失败", e));
    }


    @Override
    public Mono<CommonTokenInfo> getRedisToUserInfo(String token) {

        try {


            return loginInfoReactiveRedisTemplate.opsForValue().get(LOGIN_KEY + token)
                    .switchIfEmpty(Mono.fromRunnable(() -> {
                        // Mono是空的，执行相关动作，比如打印日志
                        log.info("查询redis,返回结果为空,参数为{}", LOGIN_KEY + token);
                    }))
                    .doOnNext(item -> item.setJti(token))
                    .doOnNext(item -> item.setAuthenticated(true))
                    .doOnNext(item -> item.setOrgId(item.getTenantId()))
                    //todo: 统一处理异常
                    .onErrorMap(e -> new JwtException("调用redis失败", e));
        } catch (Exception e) {
            log.error(e.getMessage());

        }

        return Mono.empty();

    }


}
